package controller

import (
	"context"
	"math/rand"
	"time"

	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	"2106a-zg5/demo/goods/goods_srv/models"
	proto2 "2106a-zg5/demo/goods/goods_srv/proto"
)

type GoodsService struct {
	proto2.UnimplementedGoodsServiceServer
}

func (c *GoodsService) GoodsList(ctx context.Context, req *proto2.GoodsListReq) (*proto2.GoodsListResp, error) {
	return nil, status.Errorf(codes.Unimplemented, "method GoodsList not implemented")
}
func (c *GoodsService) GoodsQuery(ctx context.Context, req *proto2.GoodsQueryReq) (*proto2.GoodsQueryResp, error) {
	return nil, status.Errorf(codes.Unimplemented, "method GoodsQuery not implemented")
}
func (c *GoodsService) GoodsUpdate(ctx context.Context, req *proto2.GoodsUpdateReq) (*proto2.GoodsUpdateResp, error) {
	return nil, status.Errorf(codes.Unimplemented, "method GoodsUpdate not implemented")
}
func (c *GoodsService) GoodsDelete(ctx context.Context, req *proto2.GoodsDeleteReq) (*proto2.GoodsDeleteResp, error) {
	return nil, status.Errorf(codes.Unimplemented, "method GoodsDelete not implemented")
}
func (c *GoodsService) GoodsCreate(ctx context.Context, req *proto2.GoodsCreateReq) (*proto2.GoodsCreateResp, error) {
	var g models.Goods
	g.Id = int64(rand.Intn(10000))
	g.GoodsName = req.Goods.GoodsName
	g.GoodsPrice = float64(req.Goods.GoodsPrice)
	g.GoodsInventory = req.Goods.GoodsInventory
	g.CreatedAt = time.Now().Format(time.DateTime)
	g.UpdatedAt = time.Now().Format(time.DateTime)
	res := models.DB.Table("goods").Create(&g)
	if res.Error != nil {
		return nil, status.Errorf(codes.Unimplemented, "创建失败")
	}
	data := modelsResponse(g)
	return &proto2.GoodsCreateResp{Goods: data}, nil
}

func modelsResponse(g models.Goods) *proto2.Goods {
	return &proto2.Goods{
		Id:             g.Id,
		GoodsName:      g.GoodsName,
		GoodsPrice:     float32(g.GoodsPrice),
		GoodsInventory: g.GoodsInventory,
	}
}
